package com.springstudy.shiro.controller;

import com.springstudy.shiro.entity.Account;
import com.springstudy.shiro.entity.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author chenrongrong
 * @since 2020/3/10 16:26
 */
@RestController
@RequestMapping(value = "login")
@Slf4j
public class LoginController {

    @PostMapping(value = "login")
    public Object login(@RequestBody Account account) {
        Subject subject = SecurityUtils.getSubject();

        try {
            UsernamePasswordToken token = new UsernamePasswordToken(account.getUsername(), account.getPassword());
            //设置是否记住用户，登录时可以通过两种方法判断
            //subject.isAuthenticated()用于判断是否执行login
            //subject.isRemembered()用户判断是否为记住用户
            token.setRememberMe(true);
            subject.login(token);

            return Response.ok();
        } catch (Exception e) {
            log.info(e.getMessage());
            return Response.fail();
        }
    }
}
